//
//  ViewController.swift
//  Guardian
//
//  Created by hushaohua on 2017/8/11.
//  Copyright © 2017年 wallstreetcn. All rights reserved.
//

import Cocoa

class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource, NSTextViewDelegate {
    
    lazy var tableView:NSTableView = {
        var aTableView = NSTableView(frame:self.view.bounds);
        aTableView.delegate = self;
        aTableView.dataSource = self;
        aTableView.rowHeight = 54;
        aTableView.intercellSpacing = NSZeroSize;
        aTableView.selectionHighlightStyle = .none;
        aTableView.gridColor = NSColor.clear;
        aTableView.allowsTypeSelect = false;
        return aTableView;
    }();

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.layer?.backgroundColor = NSColor.white.cgColor;
        // Do any additional setup after loading the view.
        
        self.setupScrollView();
        self.setupColumns();
    }
    
    override func viewWillLayout() {
        super.viewWillLayout();
        let column:NSTableColumn? = self.tableView.tableColumn(withIdentifier: "text");
        if (column != nil && column!.maxWidth != self.view.bounds.width - 20){
            column!.minWidth = self.view.bounds.width - 30;
            column!.maxWidth = self.view.bounds.width - 20;
            self.tableView.reloadData();
        }
    }
    
    func setupScrollView() -> Void {
        let scrollView:NSScrollView = NSScrollView(frame: self.view.bounds);
        scrollView.hasVerticalScroller = true;
        scrollView.autoresizingMask = [.viewWidthSizable,.viewHeightSizable];
        scrollView.contentView.documentView = self.tableView;
        self.view.addSubview(scrollView);
    }
    
    func setupColumns() -> Void{
        self.addIndexColumn();
        self.addTextColumn();
    }
    
    func addIndexColumn() -> Void {
        let column:NSTableColumn = NSTableColumn(identifier: "index");
        column.title = " ";
        column.minWidth = 20;
        column.maxWidth = 30;
//        column.resizingMask = [.userResizingMask];
        self.tableView.addTableColumn(column);
    }
    
    func addTextColumn() -> Void {
        let column:NSTableColumn = NSTableColumn(identifier: "text");
        column.title = " ";
        column.minWidth = self.view.bounds.width - 30;
        column.maxWidth = self.view.bounds.width - 20;
        column.resizingMask = [.autoresizingMask];
        self.tableView.addTableColumn(column);
    }
    
    func numberOfRows(in tableView: NSTableView) -> Int {
        return self.reuseItems.count + 1;
    }
    
    lazy var reuseItems:[GHomeKnotReuseItem] = {
        var items:[GHomeKnotReuseItem] = [GHomeKnotReuseItem]();
        return items;
    }();
    
    func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
        if (row < self.reuseItems.count){
            let reuseItem:GHomeKnotReuseItem = self.reuseItems[row];
            return CGFloat(reuseItem.rowHeight);
        }else{
            return 20;
        }
    }
    
    func tableView(_ tableView:NSTableView, indexField row:Int) -> NSTextField?{
        var textField:NSTextField? = tableView.make(withIdentifier: "index", owner: self) as? NSTextField;
        if (textField == nil){
            textField = NSTextField(frame: NSZeroRect);
            textField?.maximumNumberOfLines = 5;
            textField?.isBordered = false;
            textField?.focusRingType = .none;
        }
        textField?.font = NSFont.systemFont(ofSize: 12);
        textField?.isEditable = false;
        textField?.alignment = .right;
        textField?.textColor = NSColor.lightGray;
        textField?.stringValue = "\(row + 1)";
        return textField;
    }
    
    lazy var rowTextViews:[NSText : Any] = {
        var dict:[NSText:Any] = [NSText:Any]();
        return dict;
    }();
    
    func tableView(_ tableView:NSTableView, textView row:Int) -> NSTextView?{
        var textView:GTextView? = tableView.make(withIdentifier: "text", owner: self) as? GTextView;
        if (textView == nil){
            textView = GTextView(frame: NSZeroRect);
//            textView?.maximumNumberOfLines = 5;
            textView?.delegate = self;
//            textView?.isBordered = false;
            textView?.focusRingType = .none;
        }
        self.rowTextViews[textView!] = row;
        textView?.isEditable = true;
        textView?.textColor = NSColor.black;
        textView?.font = NSFont.systemFont(ofSize: 16);
        if (row < self.reuseItems.count){
            let reuseItem:GHomeKnotReuseItem = self.reuseItems[row];
            let knot:GKnotItem = reuseItem.sourceContent as! GKnotItem;
            textView?.string = knot.text;
        }
        return textView;
    }
    
    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        if (tableColumn?.identifier == "index"){
            return self.tableView(tableView, indexField: row);
        }else{
            return self.tableView(tableView, textView:row);
        }
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }
    
    func textShouldEndEditing(_ textObject: NSText) -> Bool {
        let tag:Int = self.rowTextViews[textObject] as! Int;
        if (self.reuseItems.count > tag){
            let reuseItem:GHomeKnotReuseItem = self.reuseItems[tag];
            let knot:GKnotItem = reuseItem.sourceContent as! GKnotItem;
            knot.text = textObject.string!;
        }
        return true;
    }
    
    func textShouldBeginEditing(_ textObject: NSText) -> Bool {
        let tag:Int = self.rowTextViews[textObject] as! Int;
        if (tag >= self.reuseItems.count){
            let reuse:GHomeKnotReuseItem = GHomeKnotReuseItem();
            let knot:GKnotItem = GKnotItem();
            reuse.sourceContent = knot;
            self.reuseItems.append(reuse);
            self.tableView.insertRows(at: IndexSet(integer:self.reuseItems.count), withAnimation: .slideUp);
        }
        return true;
    }
    
//    func textView(_ textView: NSTextView, shouldChangeTextInRanges affectedRanges: [NSValue], replacementStrings: [String]?) -> Bool{
//        let string:String = (replacementStrings?.first)!;
//        let tag:Int = self.rowTextViews[textView] as! Int;
//        if (string == "\n") {
//            let reuseItem:GHomeKnotReuseItem = self.reuseItems[tag];
//            reuseItem.lines = reuseItem.lines + 1;
//            self.tableView.noteHeightOfRows(withIndexesChanged: IndexSet(integer:tag));
//        }else if (string  == ""){
//            let nsrange:NSRange = (affectedRanges.first?.rangeValue)!;
//            let oldString:String = (textView.string?.substringFrom(nsrange))!;
//            let lines:[String] = (textView.string?.components(separatedBy: CharacterSet.newlines))!;
//            let reuseItem:GHomeKnotReuseItem = self.reuseItems[tag];
//            var lineCount:Int = lines.count;
//            if (oldString == "\n"){
//                lineCount = lineCount - 1;
//            }
//            if (lineCount != reuseItem.lines){
//                reuseItem.lines = lineCount;
//                self.tableView.noteHeightOfRows(withIndexesChanged: IndexSet(integer:tag));
//            }
//        }
//        return true;
//    }
    
    func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool{
        if (commandSelector == #selector(deleteBackward(_:))){
            let tag:Int = self.rowTextViews[textView] as! Int;
            if (self.reuseItems.count > 1 && tag > 0 && textView.string?.characters.count == 0){
                self.reuseItems.remove(at: tag);
                self.tableView.reloadData();
                return true;
            }
        }
        return false;
    }
    
    func textDidChange(_ notification: Notification) {
        guard let textView = notification.object as? NSTextView else {return}
        let tag:Int = self.rowTextViews[textView] as! Int;
        let reuseItem:GHomeKnotReuseItem = self.reuseItems[tag];
        let contentHeight:Int = Int(textView.intrinsicContentSize.height) + 8;
        if (contentHeight != reuseItem.rowHeight){
            reuseItem.rowHeight = contentHeight;
            self.tableView.noteHeightOfRows(withIndexesChanged: IndexSet(integer:tag));
        }
//        print(textView.intrinsicContentSize);
    }
}

